package com.software.usercenter.service;

import cn.hutool.json.JSONObject;
import com.software.usercenter.domain.Result;
import com.software.usercenter.entity.*;
import com.software.usercenter.exception.BizException;
import com.software.usercenter.feignclient.QuestionCenterFeignClient;
import com.software.usercenter.repository.RecordRepository;
import com.software.usercenter.repository.RoleRepository;
import com.software.usercenter.repository.UserRepository;
import com.software.usercenter.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @author : skyzo 11917
 * @date : 2023/4/24
 */
@Service
public class AdminServiceImpl implements AdminService{
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private QuestionCenterFeignClient questionCenterFeignClient;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    UserRoleRepository userRoleRepository;
    @Autowired
    RecordRepository recordRepository;

    /**
     *
     * 判断是否为管理员角色后才可以登录
     * @author skyzo 11917
     * @date  2023/4/24
     */
    @Override
    public User login(User user) {
        Optional<User> optional = userRepository.findById(user.getId());
        if(optional.isPresent()){
            User existUser = optional.get();
            if(user.getPassword().equals(existUser.getPassword())){
                Optional< UserRole> userRoleOptional=userRoleRepository.findByUserId(user.getId());
                if (userRoleOptional.isPresent()){
                    UserRole userRole=userRoleOptional.get();
                    Optional<Role> RoleOptional=roleRepository.findById(userRole.getRoleId());
                    if (RoleOptional.isPresent()){
                        Role role=RoleOptional.get();
                        if(role.getName().equals("admin"))
                            return user;
                        else
                            throw new BizException("权限不足");
                    }
                }
                throw new BizException("权限不足");
            }else{//否则抛出自定义异常 密码错误
                throw new BizException("密码错误");
            }
        }else{
            throw new BizException("该用户不存在");
        }
    }

    @Override
    public void publishQuestion(Question question) {
        //拿到查询题目总数量的json
        JSONObject questionObject=questionCenterFeignClient.findQuestionNums();
        //规定新发布的题目的id
        Object data = questionObject.get("data");
        Integer questionId=(Integer)data+1;
        //设置id
        question.setId(questionId);
        //创建新题目
        questionCenterFeignClient.createQuestion(question);
    }

    @Override
    public void deleteQuestion(Question question) {
        questionCenterFeignClient.deleteQuestion(question);
    }

    @Override
    public void updateQuestion(Question question) {
        questionCenterFeignClient.updateQuestion(question);
    }

    @Override
    public User grantPermission(String userId, String permission) {
        Optional<User> optional = userRepository.findById(userId);
        if (optional.isPresent()) {
            User existingUser = optional.get();
            Optional< UserRole> userRoleOptional=userRoleRepository.findByUserId(existingUser.getId());
            if (userRoleOptional.isPresent()) {
                UserRole userRole = userRoleOptional.get();
                throw new BizException("已经是管理员了!");
            }
            Role role=new Role();
            role.setName("admin");
            role.setId(1);
            role.setDescription("管理员");
            roleRepository.save(role);
            UserRole userRole=new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(1);
            User user=userRepository.save(existingUser);
            userRoleRepository.save(userRole);
            return user;
        } else {
            throw new BizException("用户不存在");
        }
    }

    @Override
    public List autoJudgeQuestion(Integer questionId) {
        Specification<Record> specification = new Specification<Record>() {
            @Override
            public Predicate toPredicate(Root<Record> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                //添加判断 找到题目id和答题记录表里一样的记录
                if (!StringUtils.isEmpty(questionId)) {
                    predicates.add(criteriaBuilder.equal(root.get("questionId"),questionId));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Sort.Order idOrder=Sort.Order.desc("userId");
        Sort.Order timeOrder=Sort.Order.desc("createTime");
        Sort sort=Sort.by(idOrder,timeOrder);
        List<Record> recordList=recordRepository.findAll(specification,sort);
        /*List<User> userList=userRepository.findAll();
        List<Record> needRecordList=new ArrayList<>();
        for(int i=0;i<userList.size();i++){
            int flag=0;
            String nowId = userList.get(i).getId();
            for(int j=0;j<recordList.size();j++){
                String userId=recordList.get(j).getUserId();
                if(nowId.equals(userId)){
                    needRecordList.add(recordList.get(j));
                    flag=1;
                    break;
                }
            }
            if(flag==1){

            }else{
                Record nullRecord=new Record();
                nullRecord.setUserId(nowId);
                nullRecord.setStatus("未作答");
                nullRecord.setCreateTime(new Date());
                nullRecord.setLanguage("无");
                nullRecord.setQuestionId(questionId);
                needRecordList.add(nullRecord);
            }
        }*/
        return recordList;
    }
}
